package com.xiaotu.spider.baidu.pageprocessor;

import com.xiaotu.common.model.StarBaikeWorksModel;
import com.xiaotu.common.model.StarBaikeWorksRecordModel;
import com.xiaotu.common.util.*;
import com.xiaotu.server.service.guduo.SupplementGuDuoRecordService;
import com.xiaotu.spider.AUrlPageProcessor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import us.codecraft.webmagic.Page;
import us.codecraft.webmagic.selector.Html;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @类名 StarBaikeWorksInfoPageProcessor
 * @日期 2021年2月7日
 * @作者 王艳龙
 * @功能 百度百科艺人作品列表
 */
@Component("StarBaikeWorksInfoPageProcessor")
public class StarBaikeWorksInfoPageProcessor extends AUrlPageProcessor
{
	private String start_url = "https://www.baidu.com/";

	private String filePath="D://";

	@Autowired
	private SupplementGuDuoRecordService starService;

	@Override
	protected String[] getStartRequestUrls() {
		return new String[]{start_url};
	}

	@Override
	public void process(Page page) {
		if (Constants.PageDataType.STAR_RECORD.equals(this.getPageDataType(page)))
			this.tvRecord(page);
		else
			this.pageProcess(page);
	}

	private void pageProcess(Page page) {
		Map<String,Object> param = new HashMap<String,Object>();
		param.put("rows",4500);
		param.put("page",1);
		List<Map<String,Object>> starList = starService.queryNotWorkStarInfo(param);
		for (Map<String, Object> starInfoMap : starList) {
			String linkUrl = "https://baike.baidu.com/item/"+ KeywordEncode.encode(starInfoMap.get("name")+"")+"?" +
					"starid="+starInfoMap.get("starid")+"&birthday="+KeywordEncode.encode(starInfoMap.get("birthday")+"");
			PageUtils.addTargetRequest(page, linkUrl, page.getRequest().getExtras());
		}
	}

	private void tvRecord(Page page) {
		String linkUrl = KeywordEncode.decode(page.getUrl().toString());
		String starName = null;
		String starId = null;
		String resBirthday = null;
		starName = linkUrl.substring(linkUrl.indexOf("item/")+5, linkUrl.indexOf("?starid"));
		starId = linkUrl.substring(linkUrl.indexOf("starid=")+7, linkUrl.indexOf("&birthday"));
		resBirthday = linkUrl.substring(linkUrl.indexOf("birthday=")+9, linkUrl.length());

		List<String> ddList = page.getHtml().xpath("//div[@class='basic-info']/dl/dd").all();
		List<String> dtList = page.getHtml().xpath("//div[@class='basic-info']/dl/dt/text()").all();
		if (dtList.size() == 0) {
			dtList = page.getHtml().xpath("//div[@id='baseInfoWrapDom']/div/div/div/span/text()").all();
			ddList = page.getHtml().xpath("//div[@id='baseInfoWrapDom']/div/div/div/div[@class='biContent']").all();
			if(dtList.size()==0){
				StarBaikeWorksRecordModel models = new StarBaikeWorksRecordModel();
				models.setStarId(starId);
				models.setStarName(starName);
				models.setBaikeId(null);
				models.setStatus(-1);
				page.putField(StarBaikeWorksRecordModel.class.getName(), models);
				page.putField("filePath", filePath);
				return;
			}
		}

		String birthday=null;
		for(int i=0;i<dtList.size();i++) {
			String dt = dtList.get(i);
			if (dt.equals("出生日期")) {
				birthday = BaseMsgUtils.birthString(getTextByHtml(ddList.get(i)));
				break;
			}
		}
		//获取百科id
		String BaikeId = page.getHtml().xpath("//div[@class='header-wrapper pc-header-new']//div/@data-lemmaid").get();
		//匹配库里和百度上出生日期是否一致
		resBirthday = BaseMsgUtils.birthString(resBirthday);
		if(null !=resBirthday && resBirthday.equals(birthday)){
			List<String> tvNameList = page.getHtml().xpath("//div[@class='starMovieAndTvplay']//div[@class='viewport']//ul[@class='scrollBox maqueeCanvas']" +
					"//li[@class='pages']//ul[@class='starWorksList']//li[@class='listItem']").all();
			List<String> ddAWorkList = page.getHtml().xpath("//div[@class='starMovieAndTvplay']/div[@class='viewport']/ul[@class='scrollBox maqueeCanvas']" +
					"/li[@class='pages']/ul[@class='starWorksList']/li[@class='listItem']").all();
			List<String> dtAWorkList = page.getHtml().xpath("//div[@class='starMovieAndTvplay']/div[@class='viewport']/ul[@class='scrollBox maqueeCanvas']" +
					"/li[@class='pages']/ul[@class='starWorksList']/li[@class='listItem']").all();

			if(ddAWorkList.size() ==0 || tvNameList.size() != dtAWorkList.size() || tvNameList.size() != dtAWorkList.size()){
				StarBaikeWorksRecordModel models = new StarBaikeWorksRecordModel();
				models.setStarId(starId);
				models.setStarName(starName);
				models.setBaikeId(BaikeId);
				models.setStatus(1);
				page.putField(StarBaikeWorksRecordModel.class.getName(), models);
				page.putField("filePath", filePath);
				return;
			}
			List<StarBaikeWorksModel> listModel = new ArrayList<StarBaikeWorksModel>();
			for(int i=0;i<dtAWorkList.size();i++) {
				StarBaikeWorksModel workModel = new StarBaikeWorksModel();
				workModel.setStarName(starName);
				workModel.setStarId(starId);
				Html tvNameHtml = new Html(dtAWorkList.get(i));
				String tvName = tvNameHtml.xpath("//div[@class='info']//p//b[@class='title']/a[@target='_blank']/text()").get();
				if (StringUtil.isEmpty(tvName)) {
					continue;
					//tvName = tvNameHtml.xpath("//div[@class='info']//p//b[@class='title']/text()").get();
				}
				workModel.setTvName(tvName);
				//获取作品跳转地址
				String link = tvNameHtml.xpath("//div[@class='info']//p//b[@class='title']/a[@target='_blank']/@href").get();
				workModel.setLink(link);

				Html ddWorkHtml = new Html(ddAWorkList.get(i));
				List<String> ddWorkList = ddWorkHtml.xpath("//div[@class='info']/dl/dd").all();
				Html dtWorkHtml = new Html(dtAWorkList.get(i));
				List<String> dtWorkList = dtWorkHtml.xpath("//div[@class='info']/dl/dt/text()").all();

				for (int j = 0; j < dtWorkList.size(); j++) {
					String dt = DBArrayUtils.getArrayString(getTextByHtml(dtWorkList.get(j)).replace("&nbsp;", ""));
					switch (dt) {
						case "饰演":
							String actorRole = getTextByHtml(ddWorkList.get(j));
							if (DBArrayUtils.getArrayString(actorRole) != null) {
								workModel.setActRole(DBArrayUtils.getArrayString(actorRole).replace("&nbsp;", "").replace("nbsp", ""));
							}
							break;
						case "主演":
							String mainActor = getTextByHtml(ddWorkList.get(j));
							if (DBArrayUtils.getArrayString(mainActor) != null) {
								workModel.setMainActor(DBArrayUtils.getArrayString(mainActor).replace("&nbsp;", "").replace("nbsp", ""));
							}
							break;
						case "导演":
							String director = getTextByHtml(ddWorkList.get(j));
							if (DBArrayUtils.getArrayString(director) != null) {
								workModel.setDirector(DBArrayUtils.getArrayString(director).replace("&nbsp;", "").replace("nbsp", ""));
							}
							break;
						default:
							break;
					}
				}
				listModel.add(workModel);
			}
			page.putField(StarBaikeWorksModel.class.getName(), listModel);
			page.putField("filePath", filePath);
			StarBaikeWorksRecordModel models = new StarBaikeWorksRecordModel();
			models.setStarId(starId);
			models.setStarName(starName);
			models.setBaikeId(BaikeId);
			models.setStatus(2);
			page.putField(StarBaikeWorksRecordModel.class.getName(), models);
			page.putField("filePath", filePath);


		}else{
			StarBaikeWorksRecordModel models = new StarBaikeWorksRecordModel();
			models.setStarId(starId);
			models.setStarName(starName);
			models.setBaikeId(BaikeId);
			models.setStatus(0);
			page.putField(StarBaikeWorksRecordModel.class.getName(), models);
			page.putField("filePath", filePath);
		}

	}

	@Override
	protected String getSpiderType() {
		return Constants.SpiderTaskType.STAR_BAIKE_WORKS_INFO;
	}

	@Override
	public String getPageDataType(Page page) {
		String url = page.getUrl().toString();
		if (url.contains("item"))
			return Constants.PageDataType.STAR_RECORD;
		return Constants.PageDataType.SEARCH_LIST;
	}

	public String getDateFormat(String str){
		Date date = null;
		String resDate=null;
		try {
			date = new SimpleDateFormat("yyyy-MM-dd").parse(str);
			resDate = new SimpleDateFormat("yyyy年MM月dd日").format(date);
		} catch (ParseException e) {
			e.printStackTrace();
		}
		return resDate;
	}

	/**
	 * 解析Baidu电视剧基本信息的dt和dd
	 *
	 * @param htmlStr
	 * @return
	 */
	public String getTextByHtml(String htmlStr) {
		// 过滤Baidu的标签
		while (htmlStr.contains("<sup>")) {
			String before = htmlStr.substring(0, htmlStr.indexOf("<sup>"));
			String after = htmlStr.substring(htmlStr.indexOf("</sup>") + 6, htmlStr.length());
			htmlStr = before + after;
		}
		return HtmlUtil.delHTMLTag(htmlStr);
	}

	/*public static void main(String[] args) throws ParseException {

	 *//*Date date = new SimpleDateFormat("MM-dd").parse("06-09");
		String now = new SimpleDateFormat("MM月dd日").format(date);*//*

		Date date = new SimpleDateFormat("yyyy-MM-dd").parse("1983-12-12");
		String now = new SimpleDateFormat("yyyy年MM月dd日").format(date);

		System.out.println(now);


	}*/
}
